﻿//================================================================================
//版本号：v1.0.1
//修改日期：2013-11-18
//更新内容：1、confirm对话框调用函数的参数没有更新的问题；
//          2、多Grid在翻页时遇到的问题；
//
//2014-8-6 高森
//          1、修改对话框的定位代码，解决弹出消息框时位置不在页面正中间的问题；
//          2、修改当蒙板显示时，取消掉页面的滚动条，并记录下原有body的设置；关闭蒙板时回复原有样式。

$(function () {
    //页面初始化的工作
    initButtons();
    initMask();
});

$(document).ajaxError(function (event, request, settings) {
    //hiddenLoading();
    var dlg = new Dialog();
    dlg.Type = "message";
    dlg.ID = "errorMessage";
    dlg.Title = "服务器错误-" + request.status;
    dlg.MessageText = "访问服务器发生错误,请求已终止！<br><a id='ajaxError' title='点击查看详情' href='#' >(错误详情)</a>";
    dlg.initDialog();
    dlg.show();
    $("#ajaxError").one("click", function () {
        winopen = window.open('', '', '');
        winopen.document.write(request.responseText);
    });
});

//==================================华丽的分割线=======================================
function initButtons() {
    createButton($(".btn_normal"));
}

function createButton(obj) {
    //button类型一 btn_normal
    $(obj).addClass("btn_content")
        .removeClass("btn_normal")
        .wrap(function () {
            if ($(this).attr("width")) {
                $(this).width($(this).attr("width"))
            }
            else {
                $(this).width($(this).width() + 4);
            }

            var vButton = $("<span class='btn'/>");

            var vID = $(this).attr("id");
            if (vID != null) {
                vButton = $(vButton).attr("id", vID);
                $(this).removeAttr("id");
            }

            $(vButton).mouseover(function () {
                $(this).addClass("btn_sel");
                $(this).find(".btn_right").addClass("btn_right_sel");
                $(this).find(".btn_content").addClass("btn_content_sel");
            })
            .mouseout(function () {
                $(this).removeClass("btn_sel");
                $(this).find(".btn_right").removeClass("btn_right_sel");
                $(this).find(".btn_content").removeClass("btn_content_sel");
            });

            return $(vButton);
        })
        .wrap($("<span class='btn_right'/>"));
}

//==================================华丽的分割线=======================================
//蒙板
function initMask() {
    if ($("#maskLayer").length == 0) {
        var vMask = $("<div id='maskLayer'/>").addClass("mask").css("display", "none");
        $("body").append(vMask);
    }
}

function showMask(layerIndex) {
    var vIndex = 999;
    if (!isNaN(layerIndex)) {
        vIndex = layerIndex;
    }

    $("#maskLayer").css("display", "block").css("z-index", vIndex).height($(document).height());
    var vBodyOverFlow = $("body").css("overflow");
    $("body").attr("cssbak", vBodyOverFlow);
    $("body").css("overflow", "hidden");
}

function hideMask() {
    $("#maskLayer").css("display", "none");
    $("body").css("overflow", $("body").attr("cssbak"));
}

//==================================华丽的分割线=======================================
//一些txt输入的验证




//==================================华丽的分割线=======================================
//窗口以及对话框
function Dialog() {
    var _this = this;
    _this.ID = ""; //生成的对话框ID，不能为空
    _this.Title = ""; //对话框的标题
    _this.Type = ""; //message,confirm,dialog,window
    _this.ShowMask = true; //true,false 是否显示蒙板
    _this.MessageText = ""; //当类型为message和confirm时，输出的内容
    _this.Width = "260px"; //初始宽度,类型为dialog时不需要设置该属性
    _this.Height = "120px"; //初始高度,类型为dialog时不需要设置该属性
    _this.ShowClose = true; //是否显示关闭按钮
    _this.ShowMinBtn = false; //是否显示最小化按钮
    _this.ShowMaxBtn = false; //是否显示最大化按钮
    _this.ContentObj = new Object(); //指定的html对象
    _this.ContentAlign = "center"; //对话框中内容的横向位置
    _this.ContentValign = "middle"; //对话框中内容的纵向位置
    _this.ShowMax = false; //是否默认最大化显示
    _this.NormalPositionLeft = "";
    _this.NormalPositionTop = "";
    _this.Draggable = false; //是否可以拖动
    _this.Parameter = ""; //当类型为confirm时，点击确定按钮需要的参数
    _this.ConfirmFun = null; //当类型为confirm时，点击确定按钮执行的外部方法名
    _this.Url = ""; //当类型为window的时候，需要显示的Url
    _this.ClosedFun = null; //对话框关闭时执行的方法名称

    _this.initDialog = function () {
        if (_this.ID == "") {
            alert("未设置ID值！");
            return;
        }
        CreateDialog();
    }

    _this.hide = function () {
        var vDialogID = "dlg_" + _this.ID;
        $("#" + vDialogID).hide();

        if (_this.ShowMask)
            hideMask();
        if (_this.ClosedFun != null) {
            _this.ClosedFun();
        }
    }

    _this.show = function () {
        var vDialogID = "dlg_" + _this.ID;

        var vTable = $("#" + vDialogID);
        switch (_this.Type.toLowerCase()) {
            case "message":
                $(vTable).find(".msgContext").html(_this.MessageText);
                var vBtnClose = $(vTable).find("#" + vDialogID + "_msgClose");
                $(vBtnClose).focus();
                break;
            case "confirm":
                $(vTable).find(".msgContext").html(_this.MessageText);
                $(vTable).find("#" + vDialogID + "_msgOk").focus();
                if (_this.ConfirmFun) {
                    if (_this.Parameter) {
                        $(vTable).find(".btn_ok").unbind("click").click(function () {
                            _this.ConfirmFun(_this.Parameter);
                            _this.hide();
                        });
                    }
                }
                break;
            case "dialog":
                SetBodyHeight(_this.Width, _this.Height);
                break;
            case "window":
                if (_this.ShowMax) {
                    MaxDialog();
                }
                break;
        }
        $(_this.ContentObj).show();
        $(vTable).show();

        if (_this.ShowMask)
            showMask(99);
    }

    var CreateDialog = function () {
        var vDialogID = "dlg_" + _this.ID;
        if ($("#" + vDialogID).length == 0) {//如果该对话框没有被创建
            var vTable = $("<table border='0px' cellpadding='0px' cellspacing='0px'/>").addClass("dlg").attr("id", vDialogID).css("z-index", 100001);
            var vHeadID = "dlg_" + _this.ID + "_head";
            var vHead = $("<tr/>").attr("id", vHeadID).css("cursor", "move");
            var vBody = $("<tr/>");
            var vBottom = $("<tr/>");

            var vHead_l = $("<td/>").addClass("dlg_h_l");
            var vTitle = $("<span/>").addClass("title").attr("title", _this.Title).text(_this.Title);
            var vClose = $("<div/>").addClass("close");
            var vMin = $("<div/>").addClass("min");
            var vMax = $("<div/>").addClass("max");
            var vNor = $("<div/>").addClass("nor");
            var vHead_m = $("<td/>").addClass("dlg_h_m").append(vTitle).append(vClose).append(vMax).append(vNor).append(vMin);
            var vHead_r = $("<td/>").addClass("dlg_h_r");

            var vBody_l = $("<td/>").addClass("dlg_m_l").append($("<div/>").css("height", _this.Height));
            var vBody_m = $("<td/>").addClass("dlg_m_m").css("width", _this.Width).css("height", _this.Height).attr("align", _this.ContentAlign).attr("valign", _this.ContentValign);
            var vBody_r = $("<td/>").addClass("dlg_m_r").append($("<div/>").css("height", _this.Height));

            var vBottom_l = $("<td/>").addClass("dlg_b_l");
            var vBottom_m = $("<td/>").addClass("dlg_b_m");
            var vBottom_r = $("<td/>").addClass("dlg_b_r");

            //处理内容块的显示
            switch (_this.Type.toLowerCase()) {
                case "message":
                    MessageTable(vBody_m, "message");
                    break;
                case "confirm":
                    MessageTable(vBody_m, "confirm");
                    break;
                case "dialog":
                    $(vBody_m).append($(_this.ContentObj));
                    //判断自身和插入的对象大小哪一个更大，取最大值
                    _this.Width = $(_this.ContentObj).width() > $(vBody_m).width() ? $(_this.ContentObj).width() : $(vBody_m).width();
                    _this.Height = $(_this.ContentObj).height() > $(vBody_m).height() ? $(_this.ContentObj).height() : $(vBody_m).height();
                    break;
                case "window":
                    var frame = $("<iframe height='99%' width='100%' frameborder='0'/>").attr("id", vDialogID + "_frame").attr("src", _this.Url);
                    $(vBody_m).append(frame);
                    break;
            }

            $(vHead).append(vHead_l).append(vHead_m).append(vHead_r);
            $(vBody).append(vBody_l).append(vBody_m).append(vBody_r);
            $(vBottom).append(vBottom_l).append(vBottom_m).append(vBottom_r);

            $(vTable).append(vHead).append(vBody).append(vBottom);
            $("body").append(vTable);

            if (_this.Draggable) {
                $(vTable).draggable({ handle: "#" + vHeadID });
            }
            else {
                $(vHead).css("cursor", "default");
            }

            //处理相关部件显示
            if (_this.ShowClose == false) {
                $(vClose).hide();
            }

            if (_this.ShowMinBtn == false) {
                $(vMin).hide();
            }
            else {//最小化时的处理
            }

            if (_this.ShowMaxBtn == false) {
                $(vMax).hide();
                $(vNor).hide();
            }
            else {
                $(vMax).click(function () {//最大化按钮单击事件
                    MaxDialog();
                    $(vMax).hide();
                    $(vNor).show();
                });

                $(vNor).click(function () {//还原按钮单击事件
                    NormalDialog();
                    $(vMax).show();
                    $(vNor).hide();
                });

                if (_this.ShowMax == false) {
                    $(vMax).show();
                    $(vNor).hide();
                }
                else {
                    MaxDialog();
                }
            }

            //处理相关事件
            $(vClose).click(function () {//关闭按钮单击事件
                _this.hide();
            });

            $(vTable).hide();

            //var vMarginTop = ($(window).height() - _this.Height) / 2;
            var vMarginTop = ($(window).height() - $(vTable).height()) / 2;
            newPos = new Object();
            newPos.left = ($(window).width() - $(vTable).width()) / 2;
            newPos.top = vMarginTop;

            if (vMarginTop > 0) {

            }
            else {
                newPos.top = 150;
            }

            $(vTable).offset(newPos);
        }
    }

    var SetBodyHeight = function (vWidth, vHeight) {
        var vDialogID = "dlg_" + _this.ID;
        var vTable = $("#" + vDialogID);
        var vBody_l = $(vTable).find(".dlg_m_l");
        var vBody_m = $(vTable).find(".dlg_m_m");
        var vBody_r = $(vTable).find(".dlg_m_r");

        $(vBody_m).width(vWidth).height(vHeight);
        $(vBody_l).children("div").height(vHeight);
        $(vBody_r).children("div").height(vHeight);
    }

    var MaxDialog = function () {//对话框最大化
        var vDialogID = "dlg_" + _this.ID;
        var vTable = $("#" + vDialogID);

        var vTd = $(vTable).find(".dlg_h_m");
        vMax = $(vTd).children(".max");
        vNor = $(vTd).children(".nor");
        $(vMax).hide();
        $(vNor).show();

        var vWidth = document.body.clientWidth - 32;
        var vHeight = $("html").height() - 56;

        _this.NormalPositionLeft = $(vTable).offset().left;
        _this.NormalPositionTop = $(vTable).offset().top;

        $(vTable).attr("style", "position:absolute;left:0px;top:0px;z-index:100");
        SetBodyHeight(vWidth, vHeight);
    }

    var NormalDialog = function () {//还原初始大小
        var vDialogID = "dlg_" + _this.ID;
        var vTable = $("#" + vDialogID);

        newPos = new Object();
        newPos.left = _this.NormalPositionLeft;
        newPos.top = _this.NormalPositionTop;

        $(vTable).offset(newPos);
        SetBodyHeight(_this.Width, _this.Height);
    }

    var MinDialog = function () {//对话框最小化

    }

    var MessageTable = function (vBody_m, Type) {//处理message和confirm的显示内容
        var vDialogID = "dlg_" + _this.ID;
        var vMsgTable = $("<table border='0px' cellpadding='0px' cellspacing='0px'/>").css("width", _this.Width).css("height", _this.Height);
        var vMsgText = $("<tr/>").append($("<td class='msgContext'/>").append(_this.MessageText)).css("text-align", "center").height($(vMsgTable).height() - 45);
        var vMsgContent = $("<td align='right'/>").css("height", "45px;")
        var vMsgBtnClose = $("<input type='button' class='dlg_m_btn' value='关 闭'/>").attr("id", vDialogID + "_msgClose").css("margin-right", "10px");
        if (Type == "confirm") {
            var vMsgBtnOk = $("<input type='button' class='dlg_m_btn btn_ok' value='确 定'/>").attr("id", vDialogID + "_msgOk").css("margin-left", "10px").css("margin-right", "10px");
            $(vMsgContent).append(vMsgBtnOk).attr("align", "center");

            $(vMsgBtnOk).unbind("click").click(function () {
                if (_this.ConfirmFun) {
                    if (_this.Parameter)
                        _this.ConfirmFun(_this.Parameter);
                    else
                        _this.ConfirmFun();
                }
                _this.hide();
            });
        }
        $(vMsgContent).append(vMsgBtnClose);
        var vMsgBottom = $("<tr/>").append(vMsgContent);
        $(vMsgTable).append(vMsgText).append(vMsgBottom);
        $(vBody_m).append(vMsgTable);
        $(vMsgBtnClose).click(function () {
            _this.hide();
        });
    }

    _this.changeURL = function (Url) {//改变要显示的网页地址
        var vDialogID = "dlg_" + _this.ID;
        var vTitle = $("#" + vDialogID).find(".title").text(_this.Title);
        $("#" + vDialogID + "_frame").attr("src", Url);
    }
}


//==================================华丽的分割线=======================================
//树对象
function Tree() {
    var _this = this;
    _this.ID = ""; //树生成时的ID
    _this.TextClickType = "click"; //click/expand/
    _this.TextClickFun = null; //单机文本时响应的方法名称
    //_this.TextDbClickFun = null;
    _this.ReturnType = "value"; //value/text/text:value
    _this.SelectAllChild = true; //单机父节点时是否选中它所有的子节点
    //_this.SelectChild = false;
    //_this.CheckBoxClickFun = null;
    _this.ImgWidth = "16px"; //默认图片宽度
    _this.ImgHeight = "16px"; //默认图片高度
    _this.SetNodeTextAsNodeTitle = true;

    var MaxWidth = 0;

    _this.initTree = function (itemList, parentID) {
        window.status = "";
        InitTreeParent(itemList, parentID, true);

        var expendedNode = getPageSessionStorage(_this.ID + "Expended");
        if (expendedNode && expendedNode != null) {
            expendExpendedNode(expendedNode);
        }
        var nodeSelected = getPageSessionStorage(_this.ID + "NodeSelected");
        if (nodeSelected && nodeSelected != null) {
            selectSelectedNode(nodeSelected);
        }
        $(window).unload(function () {
            removePageSessionStorageByKey(_this.ID + "Expended");
            removePageSessionStorageByKey(_this.ID + "NodeSelected");
            window.status = "";
        });

        if ($("#" + _this.ID).width() < MaxWidth)
            $("#" + _this.ID).width(MaxWidth);
    }
    var selectSelectedNode = function (selectedid) {
        var node = $("#" + selectedid);
        if (node.length == 1) {
            node.children(".treeNode_text").addClass("treeNodeSelected");
        } else {
            selectSelectedNode(selectedid.substring(0, selectedid.length - 2));
        }
    }
    var expendExpendedNode = function (expendedid) {
        var node = $("#plus_" + expendedid);
        if (node.hasClass("treeNode_plus")) {
            var ul = $("#" + expendedid).children("ul");
            node.addClass("treeNode_minus").removeClass("treeNode_plus");
            ul.show();
        }
        if (expendedid.split('_').length > 2) {
            expendExpendedNode(expendedid.substring(0, expendedid.length - 2));
        }
    }
    _this.getSelectNode = function () {

        checkList = ""; //初始化已选项列表
        var firstNodeID = _this.ID + "_0";
        //判断根节点是否被选中
        if ($("#cb_" + firstNodeID).prop("checked") == true) {
            if (_this.ReturnType == 'value') {
                checkList += $("#" + firstNodeID).attr("nodevalue") + ",";
            }
            else if (_this.ReturnType == 'text') {
                checkList += $("#" + firstNodeID).attr("nodetext") + ",";
            }
            else if (_this.ReturnType == 'text:value') {
                checkList += $("#" + firstNodeID).attr("nodetext") + ":" + $("#" + firstNodeID).attr("nodevalue") + ",";
            }
        }

        GetSelectChild($("#" + firstNodeID));
        return checkList;
    };

    var InitTreeParent = function (itemList, parentID, expand) {
        var vTree = $("<ul/>");
        if (parentID != "")
            $(vTree).css("margin-left", "16px");

        if (parentID == "") {
            $("#" + _this.ID).append(vTree);
        }
        else {
            $("#" + parentID).append(vTree);
            initExpand(vTree, expand);
        }



        if (itemList.ChildNodes.length > 0) {
            for (var ii = 0; ii < itemList.ChildNodes.length; ii++) {
                var childID = parentID + "_" + ii;
                if (parentID == "")
                    childID = _this.ID + "_" + ii;

                var childnode = itemList.ChildNodes[ii];
                //-----------------------
                //预计本结点的长度
                var vNodeWidth = (15 * childnode.Text.length) + (16 * childID.split('_').length);
                if (vNodeWidth > MaxWidth)
                    MaxWidth = vNodeWidth;

                //-----------------------
                var title = _this.SetNodeTextAsNodeTitle ? childnode.Text : childnode.Title;
                var vNode = $("<li/>").addClass("treeNode").attr("id", childID).attr("title", title).attr("nodetext", childnode.Text).attr("nodevalue", childnode.Value).attr("nodeobj", childnode.Obj);
                var vPlus = $("<span/>").attr("id", "plus_" + childID);
                if (childnode.ChildNodes.length > 0) {
                    $(vPlus).click(function () {
                        PlusClick(this);
                    });
                    $(vPlus).addClass("treeNode_minus");
                }
                else {
                    $(vPlus).addClass("treeNode_blank");
                }
                $(vNode).append(vPlus);
                //------------------------
                if (childnode.ShowCheckBox) {
                    var vChk = $("<input type='checkbox' style='margin-right:4px;'/>").attr("id", "cb_" + childID);
                    var vChkSpan = $("<span />").css("display", "table-cell").css("vertical-align", "bottom").append(vChk);
                    $(vNode).append(vChkSpan);

                    $(vChk).click(function () {
                        CheckBoxClick(this);
                    });
                }

                //------------------------
                if (childnode.ImageUrl != null) {
                    var vImg = $("<img style='margin-right:4px;'/>").attr("src", childnode.ImageUrl).attr("width", _this.ImgWidth).attr("height", _this.ImgHeight);
                    var vImgSpan = $("<span/>").css("display", "table-cell").css("vertical-align", "bottom").append(vImg);
                    $(vNode).append(vImgSpan);
                }

                //------------------------
                var vText = $("<span/>").addClass("treeNode_text").text(childnode.Text);
                if (_this.TextClickType == "expand") {
                    $(vText).css("cursor", "pointer");
                }
                else if (_this.TextClickType == "click") {
                    $(vText).css("cursor", "default");
                }

                vText.click(function () {
                    if (_this.TextClickType == "expand") {
                        PlusClick(this);
                    }
                    if (_this.TextClickFun != null && typeof (_this.TextClickFun) != "undefined") {
                        _this.TextClickFun($(this).parent("li"));
                    }

                    $(".treeNodeSelected").removeClass("treeNodeSelected");
                    var $this = $(this);
                    setPageSessionStorage(_this.ID + "NodeSelected", $this.parent().attr("id"));
                    $this.addClass("treeNodeSelected");
                    var dataOnclick = $this.attr("data-onclick");
                    window.status = $this.text();
                    if (dataOnclick) {
                        eval(dataOnclick);
                    }
                    return false;

                });

                if (childnode.ClientFunName != null && childnode.ClientFunName != "") {
                    if (childnode.ClientFunName.indexOf("(") > -1) {
                        $(vText).attr("data-onclick", childnode.ClientFunName);
                    } else {
                        $(vText).attr("onclick", childnode.ClientFunName + "(this);")
                    }
                }

                $(vNode).append(vText);
                $(vTree).append(vNode);

                InitTreeParent(childnode, childID, childnode.Expanded);
            }
        }
    }

    var PlusClick = function (vObj) {
        var vLi = $(vObj).parent("li");
        var vUl = $(vLi).children("ul");
        var vID = $(vLi).attr("id");
        var vPlus = $(vLi).children("#plus_" + vID);
        $(vUl).toggle();
        if ($(vUl).css("display") == "none") {
            $(vPlus).addClass("treeNode_plus");
            $(vPlus).removeClass("treeNode_minus");
        }
        else {
            $(vPlus).removeClass("treeNode_plus");
            $(vPlus).addClass("treeNode_minus");
            setPageSessionStorage(_this.ID + "Expended", vID);
        }
    }

    function initExpand(vObj, expand) {
        var vLi = $(vObj).parent("li");
        var vUl = $(vLi).children("ul");
        var vID = $(vLi).attr("id");
        var vPlus = $(vLi).children("#plus_" + vID);

        if (expand) {
            $(vPlus).removeClass("treeNode_plus");
            $(vPlus).addClass("treeNode_minus");
            $(vObj).show();
        }
        else {
            $(vPlus).addClass("treeNode_plus");
            $(vPlus).removeClass("treeNode_minus");
            $(vObj).hide();
        }
    }

    var CheckBoxClick = function (sel) {
        if (_this.SelectAllChild) {
            var vID = $(sel).attr("id").replace('cb_', '')
            var vLi = $("#" + vID);
            var vUl = $(vLi).children("ul");

            if ($(sel).prop("checked")) {
                $(vUl).find(":checkbox").prop("checked", "true");
            }
            else {
                $(vUl).find(":checkbox").removeAttr("checked");
            }
        }
    }

    var GetSelectChild = function (vLi) {
        var col = $(vLi).children("ul").children("li");
        for (var ii = 0; ii < col.length; ii++) {
            var vID = $(col[ii]).attr("id");
            if ($("#cb_" + vID).prop("checked") == true) {
                if (_this.ReturnType == 'value') {
                    checkList += $("#" + vID).attr("nodevalue") + ",";
                }
                else if (_this.ReturnType == 'text') {
                    checkList += $("#" + vID).attr("nodetext") + ",";
                }
                else if (_this.ReturnType == 'text:value') {
                    checkList += $("#" + vID).attr("nodetext") + ":" + $("#" + vID).attr("nodevalue") + ",";
                }
            }

            if ($("#" + vID).children("ul").length != 0)
                GetSelectChild($("#" + vID));

        }
    };
}
//==================================华丽的分割线=======================================
//grid对象
function Gird() {
    var _this = this;
    _this.ID = ""; //指定ID
    _this.MultSelect = false; //支持多选
    _this.PageSize = 10; //每页显示记录行数
    _this.IsPage = true; //是否分页取数据
    _this.SelectPage = 1; //当前选中页码
    _this.PageConut = 0; //总页数
    _this.RowCount = 0; //记录总行数
    _this.FilterString = ""; //查询条件，以and开头，可以为空
    _this.OrderColumn = ""; //排序字段
    _this.OrderType = "ASC"; //排序类型
    _this.Edit = false; //是否支持在Grid中编辑
    _this.HeadArr = new Array(); //表头属性数组
    _this.ColumnArr = new Array(); //记录行属性数组
    _this.PagePanelID = "";
    _this.vPageIndexName = ""; //是否记录页数,空的话不记录页数
    _this.RowStyleKey = "";
    _this.RowTitleKey = "";
    _this.RowClassKey = "";
    _this.RowAlternate = true; //是否采用交替行样式
    _this.ShowSequence = false; //是否显示行编号
    _this.Height = "400px"; //默认Grid高度
    _this.InitFun = null; //外部初始化方法的名称
    _this.AlignCenter = true; //默认横向居中
    _this.FixeHead = true; //默认固定表头

    function pageInit() {
        if (_this.InitFun) {
            _this.InitFun();
        }
    }

    function itemMouseOver(item) {
        $(item).addClass("grid-row-mouseover");
    }

    function itemMouseClick(item) {

    }

    function itemMouseOut(item) {
        $(item).removeClass("grid-row-mouseover");
    }

    function itemHeadClick(columnName) {
        _this.OrderColumn = columnName;
        _this.OrderType = _this.OrderType == "ASC" ? "DESC" : "ASC";
        pageInit();
    }

    function selectPage(obj) {
        _this.SelectPage = eval(obj.value);
        pageInit();
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpFirstPage() {
        _this.SelectPage = 1;
        pageInit();
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpLastPage() {
        _this.SelectPage = _this.PageConut;
        pageInit();
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpFrontPage() {
        if (_this.SelectPage > 1) {
            _this.SelectPage = eval(_this.SelectPage) - 1;
            pageInit();
        }
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function jumpNextPage() {
        if (_this.SelectPage < _this.PageConut) {
            _this.SelectPage = eval(_this.SelectPage) + 1;
            pageInit();
        }
        //记录页数
        if (_this.vPageIndexName != "") {
            setStorage(_this.vPageIndexName, _this.SelectPage);
        }
    }

    function initPageControls() {
        var vPage = $("#" + _this.ID).children(".grid-bottom"); //获取grid的bottom

        if (_this.IsPage == false) {
            $(vPage).hide();
            return;
        }

        //创建分页下拉框
        var vselpagesize = $("<select title='选择当前页显示记录的行数'><option>10</option><option>15</option><option>20</option><option>25</option><option>30</option></select>").addClass("pagesize").change(
            function () {
                _this.PageSize = eval($(this).val());
                _this.SelectPage = 1; //设置完分页数后默认加载第一页
                pageInit();
            }).val(_this.PageSize);
        //创建翻页按钮和要显示的内容
        var vsf = $("<span/>").addClass("imgbtn first").click(function () {
            jumpFirstPage();
        });
        var vsl = $("<span/>").addClass("imgbtn last").click(function () {
            jumpLastPage();
        });
        var vsn = $("<span/>").addClass("imgbtn next").click(function () {
            jumpNextPage();
        });
        var vsp = $("<span/>").addClass("imgbtn prev").click(function () {
            jumpFrontPage();
        });
        var vtxt1 = $("<span/>").css("margin-left", "10px").text("第");
        var vtxt2 = $("<span/>").css("margin-right", "10px").text("页 共 " + _this.PageConut + " 页");
        var vpi = $("<input title='敲回车翻页'/>").addClass("pagenum").one("focusin", function () {
            $(this).keydown(function (event) {
                if (event.keyCode == 13) {
                    var vpagenum = $("#" + _this.ID).find(".grid-bottom>.pagenum").val();
                    var re = /^[0-9]*[1-9][0-9]*$/;
                    if (!re.test(vpagenum)) {//判断是否为数字
                        alert("请填写正确的数字！");
                        $("#" + _this.ID).find(".grid-bottom>.pagenum").val(_this.SelectPage); //将页数改为当前页
                        return;
                    }
                    else {//判断是否超过了页数范围
                        if (eval(vpagenum) > _this.PageConut) {
                            alert("超出当前页数的最大值！");
                            $("#" + _this.ID).find(".grid-bottom>.pagenum").val(_this.SelectPage);
                            return;
                        }
                    }
                    _this.SelectPage = eval(vpagenum);
                    pageInit();
                }
            });
        });
        var vlable = $("<label/>").addClass("txt");

        $(vPage).append(vselpagesize).append($("<span class='separator'/>")).append(vsf).append(vsp).append($("<span class='separator'/>")).append(vtxt1).append(vpi).append(vtxt2).append($("<span class='separator'/>")).append(vsn).append(vsl).append($("<span class='separator'/>")).append(vlable);

        if (_this.PagePanelID != "") {//兼容以前的代码，将翻页功能加载到指定位置
            $("#" + _this.PagePanelID).html(vPage);
        }
    }

    function bindSelect() {
        if (_this.IsPage == false)
            return;
        var vgrid = $("#" + _this.ID);
        $(vgrid).find(".grid-bottom>.pagenum").val(_this.SelectPage);

        var vFirst = eval((_this.SelectPage - 1) * _this.PageSize + 1);
        var vEnd = eval(_this.SelectPage * _this.PageSize);
        if (vEnd > _this.RowCount)
            vEnd = _this.RowCount;

        var vRowCount = 0;
        if (_this.RowCount != undefined)
            vRowCount = _this.RowCount;

        var vText = "当前显示第" + vFirst + "条到" + vEnd + "条记录，一共" + vRowCount + "条";
        $(vgrid).find(".grid-bottom>.txt").text(vText);
    }

    function initHead() {
        var vTable = $("#" + _this.ID).children(".grid-head").children("table");
        var vTr = $("<tr/>");
        if (_this.ShowSequence) {
            $(vTr).append($("<th/>").append($("<div/>").addClass("grid-Sequence")));
        }

        for (var ii = 0; ii < _this.HeadArr.length; ii++) {
            var obj = eval(_this.HeadArr[ii]);
            var vTh = $("<th/>").attr("align", "center");
            var vdiv = $("<div/>")
            if (obj.width != "undefined") {
                $(vdiv).width(obj.width);
            }
            if (obj.colspan) {
                var colspan = obj.colspan;
                $(vTh).attr("colspan", colspan);
            }
            if (obj.text == "选择") {
                var vCk = $("<input id='chbCheckAll' type='checkbox' title='选中/取消选中'/>");
                $(vCk).click(function () {
                    var vTableGrid = $("#" + _this.ID).find(".grid-body>table");
                    if ($(this).prop("checked")) {
                        $(vTableGrid).find(":checkbox").prop("checked", "true");
                    }
                    else {
                        $(vTableGrid).find(":checkbox").removeAttr("checked");
                    }
                });
                $(vdiv).append(vCk);
            }
            else if (obj.orderColumn != null) {
                var vA = $("<a href='#'/>").attr("id", "headOrder_" + _this.ID).attr("orderColumn", obj.orderColumn).text(obj.text);
                $(vdiv).append(vA);
            }
            else {
                $(vdiv).text(obj.text);
            }
            $(vTh).attr("align", obj.align).append(vdiv);
            $(vTr).append(vTh);
        }
        $(vTable).append(vTr);
    }

    function initBody(DataList) {
        var vTableGrid = $("#" + _this.ID).children(".grid-body").children("table");
        for (var ii = 0; ii < DataList.length; ii++) {
            var rowStyle = "";
            if (_this.RowAlternate) {
                if (ii % 2 == 0) {
                    rowStyle = "grid-row";
                }
                else {
                    rowStyle = "grid-row-alternate";
                }
            }

            if (_this.RowClassKey && _this.RowClassKey.length > 0) {
                rowStyle += " " + (DataList[ii][_this.RowClassKey] || "");
            }

            var rowStyleKeyValue = "";
            var rowTitleKeyValue = "";
            if (_this.RowStyleKey && _this.RowStyleKey.length > 0) {
                rowStyleKeyValue = DataList[ii][_this.RowStyleKey] || "";
            }
            if (_this.RowTitleKey && _this.RowTitleKey.length > 0) {
                rowTitleKeyValue = DataList[ii][_this.RowTitleKey] || "";
            }

            var vTr = $("<tr/>").addClass(rowStyle).attr("trindex", ii).attr("style", rowStyleKeyValue).attr("title", rowTitleKeyValue);
            if (_this.ShowSequence) {
                $(vTr).append($("<td/>").append($("<div/>").html(ii + 1).addClass("grid-Sequence")));
            }

            for (var xx = 0; xx < _this.ColumnArr.length; xx++) {
                var obj = eval(_this.ColumnArr[xx]);
                var vTd = $("<td/>");
                var vdiv = $("<div/>").width(_this.HeadArr[xx].width);
                var vTemp = DataList[ii][obj.name];
                vTemp = (vTemp == null || vTemp == undefined) ? "" : vTemp;
                //var vTemp2 = "";
                if (obj.disLength != null) {
                    if (vTemp.length > obj.disLength) {
                        $(vdiv).attr("title", vTemp);
                        vTemp = vTemp.substr(0, obj.disLength) + "...";
                    }
                }

                if (obj.align != undefined) {
                    $(vTd).attr("align", obj.align);
                }

                if (obj.disabled != undefined) {
                    $(vTd).attr("disabled", obj.disabled);
                }
                var vUrl = "";
                if (obj.url != undefined) {
                    vUrl = DataList[ii][obj.url];
                }

                //disabled
                var vDisabled = "";
                if (obj.disabledKey != undefined && obj.disabledKey != null && obj.disabledKey != "") {
                    if (DataList[ii][obj.disabledKey] == "disabled" || DataList[ii][obj.disabledKey] == "True") {
                        vDisabled = "disabled";
                    }
                } else {
                    vDisabled = "";
                }

                if (obj.Title != undefined && obj.Title != null && obj.Title != "") {
                }

                switch (obj.columnType) {
                    case "lab":
                        if (_this.Edit == true && obj.edit) {
                            var vSpan = $("<span id='aLable'/>").html(vTemp);
                            var vText = $("<input type='text'>").attr("id", obj.name).addClass("txt_normal").attr("style", "display:none;width:99%").val(DataList[ii][obj.name]);
                            $(vdiv).attr("columnName", obj.name).attr("edit", obj.edit).append(vSpan).append(vText);
                        }
                        else {
                            $(vdiv).html(vTemp);
                        }
                        break;
                    case "btn":
                        if (obj.text != null)
                            vTemp = obj.text;
                        if (obj.name) {
                            vTemp = DataList[ii][obj.name];
                        }
                        if (vDisabled == "") {
                            if (_this.Edit == true && obj.edit) {
                                if (obj.text != null) {
                                    var va1 = $("<a  id='aEdit' href='#' " + vDisabled + "/>").html(vTemp);
                                    var va2 = $("<a id='aSave' href='#' onclick='" + obj.funName + "(this);' style='display:none'/>").attr("key", obj.key).attr("nodeid", DataList[ii][obj.key]).text("保存");
                                    var va3 = $("<a id='aCancle' href='#' style='display:none'/>").text("取消");
                                    $(vdiv).append(va1).append(va2).append(va3);
                                }
                                else {
                                    var va3 = $("<a id='aLable' href='#'  onclick='" + obj.funName + "(this);' " + vDisabled + "/>").html(vTemp).attr("nodeid", DataList[ii][obj.key]);
                                    var vText = $("<input type='text'>").attr("id", obj.name).addClass("txt_normal").attr("style", "display:none;width:99%").val(DataList[ii][obj.name]);
                                    $(vdiv).attr("columnName", obj.name).attr("edit", obj.edit).append(va3).append(vText);
                                }
                            }
                            else {
                                var va4 = $("<a href='#' onclick='" + obj.funName + "(this);' " + vDisabled + "/>").attr("key", obj.key).attr("nodeid", DataList[ii][obj.key]).attr("url", vUrl).html(vTemp);
                                if (obj.name) {
                                    va4 = $("<a href='#' onclick='" + obj.funName + "(this);' " + vDisabled + "/>").attr("key", obj.key).attr("nodeid", DataList[ii][obj.key]).attr("url", vUrl).html(vTemp); ;
                                }

                                $(vdiv).append(va4);
                            }
                        }
                        break;
                    case "img":
                        var vImg = $("<img height='16px' width='16px'/>").attr("src", "../" + DataList[ii][obj.src]);
                        $(vdiv).append(vImg);
                        break;
                    case "imgBtn":
                        if (obj.imgSrc) {
                            var visible = true;
                            if (obj.imgVisibleKey) {
                                visible = DataList[ii][obj.imgVisibleKey];
                            }
                            if (visible) {
                                var vImg = $("<img/>").attr("src", "../" + obj.imgSrc);

                                vImg.css("height", obj.imgHeight || 16);
                                vImg.css("width", obj.imgHeight || 16);

                                if (obj.key && obj.key != "") {
                                    vImg.attr("data-key", DataList[ii][obj.key]);
                                }
                                if (obj.funName && obj.funName != "") {
                                    vImg.attr("data-oper", obj.funName);
                                }
                                $(vdiv).append(vImg);
                            }
                        }
                        break;
                    case "chb":
                        var vCk = $("<input type='checkbox'/>").attr("id", "chb" + ii);
                        if (DataList[ii][obj.name]) {
                            $(vCk).attr("checked", " checked");
                        }

                        $(vCk).attr("nodeid", DataList[ii][obj.key]);
                        if (obj.funName) {
                            $(vCk).attr("onclick", obj.funName + "(this)");
                        }
                        $(vdiv).append(vCk);
                        break;
                    default:
                        $(vdiv).html(DataList[ii][obj.name]);
                }
                $(vTd).append(vdiv);
                $(vTr).append(vTd);
            }
            $(vTableGrid).append(vTr);
        }
    }

    function itemRowEdit(item) {
        var vtr = $(item).parent("td").parent("tr").children();

        //处理其他可编辑行的状态
        var vTop = $(item).parent("td").parent("tr").parent().children("tr").children();
        $(vTop).children(":text").css("display", "none");
        $(vTop).children("[id='aLable']").css("display", "block");
        $(vTop).children("[id='aEdit']").css("display", "block");
        $(vTop).children("[id='aSave']").css("display", "none");
        $(vTop).children("[id='aCancle']").css("display", "none");

        $(vtr).children("[id='aLable']").css("display", "none");
        $(vtr).children(":text").css("display", "block");

        var vObj = $(item).parent("td").children("a");
        for (var ii = 0; ii < vObj.length; ii++) {
            if ($(vObj[ii]).attr("id") == "aEdit") {
                $(vObj[ii]).css("display", "none");
            }
            else {
                $(vObj[ii]).css("display", "block");
            }
        }
    }

    function itemRowCancle(item) {
        var vtr = $(item).parent("td").parent("tr").children();

        $(vtr).children("[id='aLable']").css("display", "block");
        $(vtr).children(":text").css("display", "none");

        var vObj = $(item).parent("td").children("a");
        for (var ii = 0; ii < vObj.length; ii++) {
            if ($(vObj[ii]).attr("id") == "aEdit") {
                $(vObj[ii]).css("display", "block");
            }
            else {
                $(vObj[ii]).css("display", "none");
            }
        }
    }

    _this.getModel = function () {
        if (_this.IsPage == false)
            _this.PageSize = 0;

        var vModel = { PageSize: _this.PageSize,
            SelectPage: _this.SelectPage,
            FilterString: _this.FilterString,
            OrderColumn: _this.OrderColumn,
            OrderType: _this.OrderType
        };

        return vModel;
    }

    _this.itemRowSave = function (item) {
        var vtr = $(item).parent("td").parent("tr");
        var vString = "{\"" + $(item).attr("key") + "\":\"" + $(item).attr("nodeid") + "\"";
        var vObj = $(vtr).children("[edit='true']");
        for (var ii = 0; ii < vObj.length; ii++) {
            vString += ",\"" + $(vObj[ii]).attr("columnName") + "\":\"" + $(vObj[ii]).children("input").val() + "\"";
        }
        vString += "}";
        return eval("(" + vString + ")");
    }

    _this.initGrid = function (response) {
        if (_this.ID == "") {
            alert("请设置Grid的ID！");
            return;
        }

        //基于当前情况，替换顶层table标签为div        
        $("#" + _this.ID).replaceWith($("<div id='" + _this.ID + "'/>").addClass("grid"));

        var vgrid = $("#" + _this.ID);

        if (_this.AlignCenter) {
            $(vgrid).css("margin", "0 auto");
        }

        $(vgrid).html('');
        $(vgrid).append($("<div/>").addClass("grid-head").append($("<table/>").attr("cellspacing", "0px").attr("cellpadding", "0px")));
        $(vgrid).append($("<div/>").addClass("grid-body").append($("<table/>").attr("cellspacing", "0px").attr("cellpadding", "0px")));

        $(vgrid).append($("<div/>").addClass("grid-bottom"));
        //获取行数和页数
        _this.RowCount = response.Count;
        _this.PageConut = Math.ceil(_this.RowCount / _this.PageSize);
        //创建grid头
        initHead();

        //设置grid的宽度
        var vgridWidth = $(vgrid).find(".grid-head>table").width();
        $(".grid-body").css("overflow-y", "hidden");
        if (_this.IsPage) {
            //设置body的高度
            if (_this.FixeHead) {
                $(".grid-body").height(_this.Height);
                vgridWidth = eval(vgridWidth) + 20;
                $(".grid-body").css("overflow-y", "scroll");
            }
        }
        $(vgrid).width(vgridWidth);

        //创建Body
        if (response.ListResult != undefined) {
            initBody(response.ListResult);
            $("[data-oper]").click(function () {
                var $this = $(this);
                var dataOper = $this.attr("data-oper");
                eval(dataOper + "(this)");
            });
        }
        //创建Bottom
        initPageControls();
        bindSelect();

        //添加排序事件
        $("#headOrder_" + _this.ID).click(function () {
            itemHeadClick($(this).attr("orderColumn"));
        });

        var vbody = $(vgrid).children(".grid-body");

        $(vbody).find("tr").bind('mouseover', function () {
            itemMouseOver(this);
        });

        $(vbody).find("tr").bind('mouseout', function () {
            itemMouseOut(this);
        });

        $(vbody).find("tr").click(function () {
            itemMouseClick(this);
        })

        $(vbody).find("#aEdit").bind('click', function () {
            itemRowEdit(this);
        });

        $(vbody).find("#aCancle").bind('click', function () {
            itemRowCancle(this);
        });

        //添加首页 上一页 下一页 末页是否可用
        if (_this.SelectPage == 1) {
            $("#firstPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
            $("#frontPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
        }
        if (_this.SelectPage == _this.PageConut) {
            $("#nextPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
            $("#lastPage_" + _this.ID).attr("disabled", "disabled").unbind("click");
        }
    }
}


//获取事件
function getEvent() {
    if (document.all) return window.event;
    func = getEvent.caller;
    while (func != null) {
        var arg0 = func.arguments[0];
        if (arg0) {
            if ((arg0.constructor == Event || arg0.constructor == MouseEvent)
             || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                return arg0;
            }
        }
        func = func.caller;
    }
    return null;
}
//清除所有页面存储
function clearAllPageSessionStorage() {
    if (window.sessionStorage) {
        window.sessionStorage.clear();
    }
}
//设置
function setPageSessionStorage(key, value) {
    if (window.sessionStorage) {
        window.sessionStorage[key] = value;
    } else {
        $(document).data(key, value);
    }
}
//获取
function getPageSessionStorage(key) {
    if (window.sessionStorage) {
        return window.sessionStorage[key];
    } else {
        return $(document).data(key); ;
    }
}

function removePageSessionStorageByKey(key) {
    if (window.sessionStorage) {
        window.sessionStorage.removeItem(key);
    }
}

function QueryString(QueryName) {
    ///	<summary>
    ///	通用方法-获取网页地址中的参数
    ///	</summary>
    ///	<param name="QueryName" type="String">参数名</param>
    ///	<returns type="String"></returns>
    //构造参数对象并初始化
    var name, value = '', i;
    var str = location.href.toString(); //获得浏览器地址栏URL串
    str = str.replace("#", "&");
    var num = str.indexOf("?");
    str = str.substr(num + 1); //截取“?”后面的参数串
    var arrtmp = str.split("&"); //将各参数分离形成参数数组
    for (i = 0; i < arrtmp.length; i++) {
        num = arrtmp[i].indexOf("=");
        if (num > 0) {
            name = arrtmp[i].substring(0, num); //取得参数名称
            value = arrtmp[i].substr(num + 1); //取得参数值
            if (name.toUpperCase() == QueryName.toUpperCase()) {
                return decodeURI(value).replace("#", "");
            }
        }
    }
    return "";
}
